<template>
  <view class="container">
    <view class="wechatapp">
      <view class="header">
        <image class="avatar" :src="userAvatar || '/static/default-avatar.png'" mode="aspectFill"></image>
      </view>
    </view>
    <view class="auth-title">完善个人信息</view>
    
    <!-- 头像昵称填写区域 -->
    <view v-if="!isProfile" class="user-info-form">
      <view class="form-item">
        <view class="form-label">头像</view>
        <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="form-avatar" :src="userAvatar || '/static/default-avatar.png'" mode="aspectFill"></image>
          <view class="avatar-tip">点击选择头像</view>
        </button>
      </view>
      
      <view class="form-item">
        <view class="form-label">昵称</view>
        <input 
          class="nickname-input" 
          type="nickname" 
          v-model="userNickname" 
          placeholder="请输入昵称"
          @blur="onNicknameBlur"
          maxlength="20"
        />
      </view>
      
      <view class="login-btn">
        <button class="button btn-normal" @click.stop="completeUserInfo" :disabled="!canSubmit">完成注册</button>
      </view>
    </view>
    
    <!-- 手机号授权区域 -->
    <view v-if="isProfile">
        <view class="auth-subtitle">获得您微信绑定的手机号码</view>
        <view class="login-btn">
          <button class="button-mobile btn-primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权手机号</button>
        </view>
    </view>
    
    <view class="no-login-btn">
      <button class="button btn-normal" @click="cancelLogin">暂不登录</button>
    </view>
    
    <view class="privacy">
        <label @click="privacyChange"><checkbox :checked="agreePrivacy" value="agree" color="#fa2209" style="transform:scale(0.7)"/>已阅读并同意</label>
        <text class="privacy-ptl" @click="openPrivacy(1)">《隐私协议》</text>
        <text class="member-ptl" @click="openPrivacy(2)">《用户协议》</text>
        <wx-privacy ref="popPrivacy" @agree="handleAgree" :title="protocolTitle" :subDesc="protocolSubDesc" @disagree="handleDisagree"></wx-privacy>
    </view>
    
  </view>
</template>

<script>
  import store from '@/store'
  import * as UserApi from '@/api/user'
  import WxPrivacy from './wx-privacy'
  import ProtocolEnum from '@/common/enum/protocol/Protocol'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  export default {
    components: {
      WxPrivacy
    },
    data() {
      return {
        // 微信小程序登录凭证 (code)
        // 提交到后端，用于换取openid
        code: '',
        needPhone: false,
        isProfile: false,
        isOpenPrivacy: false,
        agreePrivacy: false,
        protocolTitle: '',
        protocolSubDesc: '',
        ProtocolEnum,
        SettingKeyEnum,
        // 新增用户信息字段
        userAvatar: '',
        userNickname: '',
        avatarFile: null
      }
    },

    computed: {
      // 是否可以提交
      canSubmit() {
        return this.agreePrivacy && this.userNickname.trim().length > 0
      }
    },

    created() {
      // 获取code
      this.getCode()
      
      // 获取配置
      this.getUserSetting()
    },

    methods: {
      privacyChange() {
         this.agreePrivacy = !this.agreePrivacy;
      },
      openPrivacy(type) {
         if (type == 1) {
             this.protocolTitle = ProtocolEnum.data[0].name;
             this.protocolSubDesc = ProtocolEnum.data[0].value;
         } else {
             this.protocolTitle = ProtocolEnum.data[1].name;
             this.protocolSubDesc = ProtocolEnum.data[1].value;
         }
         this.$refs.popPrivacy.openPrivacy();
      },
      handleDisagree() {
         this.agreePrivacy = false;
         this.$refs.popPrivacy.closePrivacy();
      },
      handleAgree() {
         this.agreePrivacy = true;
         this.$refs.popPrivacy.closePrivacy();
      },

      // 获取code
      // https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
      getCode() {
        return new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: res => {
              console.log('getCode res = ', res)
              resolve(res.code)
            },
            fail: reject
          })
        })
      },
      
      getUserSetting() {
        const app = this
        return new Promise((resolve, reject) => {
            UserApi.setting()
            .then(result => {
                app.needPhone = result.data.loginNeedPhone === 'true' ? true : false
            })
            .catch(err => {
              // empty
            })
        })
      },

      // 选择头像回调
      onChooseAvatar(e) {
        const { avatarUrl } = e.detail
        this.userAvatar = avatarUrl
        console.log('选择头像:', avatarUrl)
      },

      // 昵称输入完成
      onNicknameBlur(e) {
        this.userNickname = e.detail.value.trim()
      },

      // 完成用户信息填写
      async completeUserInfo() {
        const app = this
        if (!app.canSubmit) {
          app.$error("请完善个人信息并同意用户协议")
          return
        }

        try {
          // 构造用户信息
          const userInfo = {
            nickName: app.userNickname,
            avatarUrl: app.userAvatar,
            type: "new_auth" // 标识新的授权方式
          }

          if (app.needPhone) {
            app.isProfile = true
            // 保存用户信息，等待手机号授权
            app.tempUserInfo = userInfo
          } else {
            // 直接登录
            app.onAuthSuccess(userInfo)
          }
        } catch (error) {
          console.error('完善用户信息失败:', error)
          app.$error("信息提交失败，请重试")
        }
      },

      // 获取微信用户信息（兼容旧版本）
      getUserProfile() {
        const app = this;
        if (!app.agreePrivacy) {
            app.$error("请仔细阅读《用户协议》和《隐私协议》，点击同意代表您已认上述协议内容！");
            return false;
        }
        // 新版本直接显示用户信息填写界面
        console.log('使用新版授权流程')
      },
      
      // 获取微信绑定的手机号
      getPhoneNumber(e) {
          if (e.detail.errMsg == "getPhoneNumber:ok") {
             this.onAuthSuccess({"type": "phone", "encryptedData": e.detail.encryptedData, "iv": e.detail.iv, "sessionKey": e.detail.iv})
          }
      },
      
      // 授权成功事件
      // 这里分为两个逻辑:
      // 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
      // 2.如果不存在该用户, 则显示注册页面, 需填写手机号
      async onAuthSuccess(userInfo) {
        const app = this
        // 提交到后端
        store.dispatch('MpWxLogin', { code: await app.getCode(), shareId: (uni.getStorageSync('shareId') ? uni.getStorageSync('shareId') : 0), userInfo })
          .then(result => {
            if (!app.needPhone || userInfo.type == "phone") {
                // 显示登录成功
                app.$toast(result.message)
                // 跳转回原页面
                setTimeout(() => {
                  app.onNavigateBack()
                }, 1000)
            } else {
                store.dispatch('Logout')
            }
          })
          .catch(() => {
            // 将oauth提交给父级
            app.onEmitSuccess(userInfo)
          })
      },

      // 将oauth提交给父级
      // 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
      async onEmitSuccess(userInfo) {
        const app = this
        app.$emit('success', {
          oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
          code: await app.getCode(), // 微信登录的code, 用于换取openid
          userInfo // 微信用户信息
        })
      },

      /**
       * 暂不登录
       */
      cancelLogin() {
        // 跳转回原页面
        this.onNavigateBack();
      },

      /**
       * 授权成功 跳转回原页面
       */
      onNavigateBack(delta = 1) {
        uni.navigateBack({
          delta: Number(delta)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 0 60rpx;
    font-size: 32rpx;
    background: #fff;
    min-height: 100vh;
  }

  .wechatapp {
    padding: 80rpx 0 48rpx;
    border-bottom: 1rpx solid #e3e3e3;
    margin-bottom: 72rpx;
    text-align: center;

    .header {
      width: 190rpx;
      height: 190rpx;
      border: 4rpx solid #fff;
      margin: 0 auto 0;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);
    }
  }

  .auth-title {
    color: #585858;
    font-size: 34rpx;
    margin-bottom: 40rpx;
  }

  .auth-subtitle {
    color: #888;
    margin-bottom: 88rpx;
    font-size: 28rpx;
  }

  .login-btn {
    padding: 0 20rpx;

    .button {
      height: 88rpx;
      line-height: 88rpx;
      background: $fuint-theme;
      color: #fff;
      font-size: 30rpx;
      border-radius: 12rpx;
      text-align: center;
    }
    .button-mobile {
        height: 88rpx;
        line-height: 88rpx;
        background: $fuint-theme;
        color: #fff;
        font-size: 30rpx;
        border-radius: 12rpx;
        text-align: center;
    }
  }


  .no-login-btn {
    margin-top: 24rpx;
    padding: 0 20rpx;

    .button {
      height: 88rpx;
      line-height: 88rpx;
      background: #dfdfdf;
      color: #fff;
      font-size: 30rpx;
      border-radius: 12rpx;
      text-align: center;
    }
  }
  
  .privacy {
      margin-top: 50rpx;
      padding-left: 5rpx;
      font-size: 24rpx;
      text-align: center;
      .member-ptl {
          color: $fuint-theme;
      }
      .privacy-ptl {
          color: $fuint-theme;
      }
  }

  // 新增用户信息填写样式
  .user-info-form {
    margin-bottom: 40rpx;
  }

  .form-item {
    margin-bottom: 40rpx;
    padding: 0 20rpx;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .avatar-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    background: transparent;
    border: none;
    padding: 0;
    
    .form-avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      border: 2rpx solid #e0e0e0;
    }
    
    .avatar-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }

  .nickname-input {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    background: #fff;
  }

  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }

  .button:disabled {
    background: #ccc !important;
    color: #999 !important;
  }
</style>
